import * as path from 'path';
import axios from 'axios';
import * as cheerio from 'cheerio';
import { taskCenter, dbDownFile } from '../tools';
import DB from '../db/modules';

// downOneList('http://153na.com/tupianqu/KSE/list103.html');

export function downOneList(url) {
  console.count('*************大列表***********');
  console.log(url);
  let t = () => {
    return axios
      .get(url, {
        timeout: 10000
      })
      .then(res => {
        let $ = cheerio.load(res.data);
        let cagetory = $('.mod-title > h3').text();
        $('#colList ul li a').each(async (idx, ele) => {
          let a = downOneGropImgs.bind(
            null,
            'http://153na.com' + $(ele).attr('href'),
            cagetory
          );
          a.other = {
            url: 'http://153na.com' + $(ele).attr('href'),
            descript: '列表'
          };
          taskCenter.add(a);
        });
      });
  };

  //@ts-ignore
  t.other = {
    url,
    descript: '一列的图片列表'
  };
  taskCenter.add(t);
}
export async function downOneGropImgs(url, category) {
  let oneImageGroup = await DB.ImageGroup.findOne({
    target_url: url
  });

  if (oneImageGroup) {
    let list = await DB.Resource.find({
      parent_id: oneImageGroup._id
    });

    if (list.length) {
      list.map(item => {
        dbDownFile({
          url: item.target_url,
          localPath: item.url,
          parentId: oneImageGroup._id,
          index: item.index
        });
      });
      return;
    }
  }

  let { dir, root, base, name, ext } = path.parse(url);
  return axios
    .get(url, {
      timeout: 10000
    })
    .then(async res => {
      let $ = cheerio.load(res.data);
      let name = $('.h1-title').text();
      if (!oneImageGroup) {
        //  创建
        oneImageGroup = await DB.ImageGroup.create({
          category,
          type: 'image',
          name,
          target_url: url,
          url: '', // 资源的本地地址
          is_down: true, // 是否下载到本地
          fail_number: 0, // 资源下载的失败次数
          down_time: 0, //下载次数
          parent_id: '',
          loading: false,
          index: 0
          // images
        });
        console.count('新增列表次数');
      }

      $('.main-content img').map((idx, ele) => {
        let url = $(ele).attr('src');
        let { dir, root, base, ext } = path.parse(url);

        dbDownFile({
          url,
          localPath: `resources/imgs/${name}/${idx}${ext}`.trim(),
          parentId: oneImageGroup._id,
          index: idx,
          category,
          type: 'image'
        });
      });
    });
}
